package com.example.petstore_2.aspect;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.petstore_2.common.CommonResponse;
import com.example.petstore_2.util.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

public class JWTInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中令牌
        String token = request.getHeader("Authorization");
        String msg = "";
        CommonResponse commonResponse;
        response.setContentType("application/json;charset=UTF-8");
        try {
            System.out.println("验证");
            JWTUtil.verify(token);
            return true;  // 放行请求
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            msg = "无效签名";
            commonResponse = CommonResponse.creatForError(msg);
            String json = new ObjectMapper().writeValueAsString(commonResponse);
            response.getWriter().println(json);
            return false;
        }catch (TokenExpiredException e){
            e.printStackTrace();
            msg = "token过期";
            commonResponse = CommonResponse.creatForError(msg);
            String json = new ObjectMapper().writeValueAsString(commonResponse);
            response.getWriter().println(json);
            return false;
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            msg = "算法不一致";
            commonResponse = CommonResponse.creatForError(msg);
            String json = new ObjectMapper().writeValueAsString(commonResponse);
            response.getWriter().println(json);
            return false;
        }catch (Exception e){
            e.printStackTrace();
            msg = "token无效";
            commonResponse = CommonResponse.creatForError(msg);
            String json = new ObjectMapper().writeValueAsString(commonResponse);
            response.getWriter().println(json);
            return false;
        }
    }
}
